package cn.stylefeng.guns.sys.modular.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.stylefeng.guns.base.auth.context.LoginContextHolder;
import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.sys.core.exception.BusException;
import cn.stylefeng.guns.sys.core.exception.enums.BusExceptionEnum;
import cn.stylefeng.guns.sys.core.util.DateUtil;
import cn.stylefeng.guns.sys.core.util.ExcelFormatUtil;
import cn.stylefeng.guns.sys.modular.system.controller.BaseFrontController;
import cn.stylefeng.guns.sys.modular.system.entity.BusConst;
import cn.stylefeng.guns.sys.modular.system.entity.CaiwuPankui;
import cn.stylefeng.guns.sys.modular.system.entity.Huopei;
import cn.stylefeng.guns.sys.modular.system.mapper.CaiwuPankuiMapper;
import cn.stylefeng.guns.sys.modular.system.mapper.HuopeiMapper;
import cn.stylefeng.guns.sys.modular.system.mapper.UserMapper;
import cn.stylefeng.guns.sys.modular.system.model.HuopeiDto;
import cn.stylefeng.guns.sys.modular.system.service.HuopeiService;
import cn.stylefeng.guns.sys.modular.system.service.WeChatSendTempMsgService;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

import static cn.afterturn.easypoi.util.PoiCellUtil.getCellValue;

@Service
public class HuopeiServiceImpl extends ServiceImpl<HuopeiMapper, Huopei> implements HuopeiService {

    Logger logger = LoggerFactory.getLogger(HuopeiServiceImpl.class);

    private static final Logger log = LoggerFactory.getLogger(HuopeiServiceImpl.class);

    @Autowired
    private HuopeiMapper huopeiMapper;
    @Autowired
    private UserMapper userMapper;
    @Resource
    private WeChatSendTempMsgService weChatSendTempMsgService;
    @Autowired
    private CaiwuPankuiMapper pankuiMapper;

    /**
     * 导入excel
     */
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public Boolean batchImport(String fileName, MultipartFile file) throws Exception {

        boolean notNull = false;
        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
            throw new Exception("上传文件格式不正确");
        }

        boolean isExcel2003 = true;//Excel2003
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }

        InputStream is = file.getInputStream();
        Workbook wb = null;
        if (isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }


        //excel中多个sheet表，获取所有sheet表的数量
        int sheets = wb.getNumberOfSheets();
        for (int i = 0; i < sheets; i++) {
            Sheet sheet = wb.getSheetAt(i);
            if (sheet != null) {
                notNull = true;
            }

            Row row1 = sheet.getRow(0);
            String name = row1.getCell(0).getStringCellValue();
            String begin = name.split("业务日期:|至|\\)")[1];
            String end = name.split("业务日期:|至|\\)")[2];

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date beginTime = sdf.parse(begin);
            Date endTime = sdf.parse(end);


            //shopCode集合
            List<String> codeList = new ArrayList();

            List<Huopei> huopeiList = new ArrayList();


            //循环行row
            int lastRowNum = sheet.getLastRowNum() - 1;
            for (int r = 2; r <= lastRowNum; r++) {
                Row row = sheet.getRow(r);
                if (row == null) {
                    continue;
                }

                //获取单元格
                Cell cell = row.getCell(0);
                if (ToolUtil.isNotEmpty(cell)) {
                    cell.setCellType(CellType.STRING);
                }


                String number = row.getCell(0) == null ? "" : row.getCell(0).getStringCellValue();//序号
                String shopCode = row.getCell(1) == null ? "" : row.getCell(1).getStringCellValue();//门店编号
                String shopName = row.getCell(2) == null ? "" : row.getCell(2).getStringCellValue();//门店名称
                String className = row.getCell(3) == null ? "" : row.getCell(3).getStringCellValue();//品项类别名称
                String proCode = row.getCell(4) == null ? "" : row.getCell(4).getStringCellValue();//品项编号
                String proName = row.getCell(5) == null ? "" : row.getCell(5).getStringCellValue();//品项名称
                String spec = row.getCell(6) == null ? "" : row.getCell(6).getStringCellValue();//规格
                String unit = row.getCell(7) == null ? "" : row.getCell(7).getStringCellValue();//单位
                //非税单价
                String price = getCellValue(row.getCell(8));
                //理论耗用数量
                String thNum = getCellValue(row.getCell(9));
                //实际耗用数量
                String realNum = getCellValue(row.getCell(10));
                //耗用数量分差
                String numTotal = getCellValue(row.getCell(11));
                //耗用金额分差
                String amountTotal = getCellValue(row.getCell(12));
                Long createUser = LoginContextHolder.getContext().getUserId();//创建者
                Date createTime = new Date();//创建时间


//                int cjAm = 0;
//                int cjNum = 0;
//                int dhAm = 0;
//                int dhNum = 0;
//                int jlAm = 0;
//                int jlNum = 0;
//                int jsAm = 0;
//                int jsNum = 0;

//                if (className.equals("餐具（实收资本）")){
//                    cjAm = cjAm + amount;
//                    cjNum = cjNum + num;
//                }else if (className.equals("冻货")){
//                    dhAm = dhAm + amount;
//                    dhNum = dhNum + num;
//
//                }else if (className.equals("酱料")){
//                    jlAm = jlAm + amount;
//                    jlNum = jlNum + num;
//
//                }else if (className.equals("酒水")){
//                    jsAm = jsAm + amount;
//                    jsNum = jsNum + num;
//
//                }
//                //餐具（实收资本）金额分差小计
//                cjAmSum = String.valueOf(cjAm);
//                //餐具（实收资本）数量分差小计
//                cjNumSum = String.valueOf(cjNum);
//
//                //冻货金额分差小计
//                dhAmSum = String.valueOf(dhAm);
//                //冻货数量分差小计
//                dhNumSum = String.valueOf(dhNum);
//
//                //酱料金额分差小计
//                jlAmSum = String.valueOf(jlAm);
//                //酱料数量分差小计
//                jlNumSum = String.valueOf(jlNum);
//
//                //酒水金额分差小计
//                jsAmSum = String.valueOf(jsAm);
//                //酒水数量分差小计
//                jsNumSum = String.valueOf(jsNum);


                if (ToolUtil.isNotEmpty(shopCode)){
                    Huopei huopei = new Huopei();
                    huopei.setNum(number);
                    huopei.setShopCode(shopCode);
                    huopei.setShopName(shopName);
                    huopei.setClassName(className);
                    huopei.setProCode(proCode);
                    huopei.setProName(proName);
                    huopei.setSpec(spec);
                    huopei.setUnit(unit);
                    huopei.setPrice(price);
                    huopei.setThNum(thNum);
                    huopei.setRealNum(realNum);
                    huopei.setNumTotal(numTotal);
                    huopei.setAmountTotal(amountTotal);
                    huopei.setCreateUser(createUser);
                    huopei.setCreateTime(createTime);
                    huopei.setStatus(1);//审核状态;1财务上传,2店长审核,3财务审核,4推送人事
                    huopei.setBeginTime(beginTime);
                    huopei.setEndTime(endTime);

                    huopeiList.add(huopei);
                    codeList.add(shopCode);
                }

//                huopeiMapper.insert(huopei);
            }

            for (String code : codeList) {
                //查询数据库中是否存在该店该时间段的数据
                int num = huopeiMapper.count(code, beginTime);
                if (num != 0){
                    //删除货赔表数据
                    huopeiMapper.delete(code, beginTime);
                    //查询盘亏表是否存在该店该时间段的数据
                    int count = pankuiMapper.count(code, beginTime);
                    if (count != 0){
                        //删除盘亏表数据
                        pankuiMapper.delete(code, beginTime);
                    }

                }
            }

            for (Huopei huopei : huopeiList) {
                huopeiMapper.insert(huopei);
            }


//            for (String code : codeList) {
//                Huopei huopei = new Huopei();
//                huopei.setCjNumSum(cjNumSum);
//                huopei.setCjAmSum(cjAmSum);
//                huopei.setDhNumSum(dhNumSum);
//                huopei.setDhAmSum(dhAmSum);
//                huopei.setJlNumSum(jlNumSum);
//                huopei.setJlAmSum(jlAmSum);
//                huopei.setJsNumSum(jsNumSum);
//                huopei.setJsAmSum(jsAmSum);
//                huopei.setShopCode(code);
//                huopeiMapper.update(huopei);
//            }


        }
        return notNull;
    }

    @Override
    public List<Huopei> listExport(String dm, Date date) {
        return huopeiMapper.listExport(dm, date);
    }


    /**
     * 判断指定的单元格是否是合并单元格
     *
     * @param sheet
     * @param row    行下标
     * @param column 列下标
     * @return
     */
    private boolean isMergedRegion(Sheet sheet, int row, int column) {

        int sheetMergeCount = sheet.getNumMergedRegions();
        for (int i = 0; i < sheetMergeCount; i++) {

            CellRangeAddress range = sheet.getMergedRegion(i);
            int firstColumn = range.getFirstColumn();// 合并单元格CELL起始列
            int lastColumn = range.getLastColumn();// 合并单元格CELL结束列
            int firstRow = range.getFirstRow();// 合并单元格CELL起始行
            int lastRow = range.getLastRow();// 合并单元格CELL结束行
            if (row >= firstRow && row <= lastRow) {
                if (column >= firstColumn && column <= lastColumn) {
                    int retVal = lastRow - firstRow + 1;// 得到合并的行数
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 获取合并单元格的值
     *
     * @param sheet
     * @param row
     * @param column
     * @return
     */
    public String getMergedRegionValue(Sheet sheet, int row, int column) {

        int sheetMergeCount = sheet.getNumMergedRegions();

        for (int i = 0; i < sheetMergeCount; i++) {
            CellRangeAddress ca = sheet.getMergedRegion(i);
            int firstColumn = ca.getFirstColumn();
            int lastColumn = ca.getLastColumn();
            int firstRow = ca.getFirstRow();
            int lastRow = ca.getLastRow();

            if (row >= firstRow && row <= lastRow) {

                if (column >= firstColumn && column <= lastColumn) {
                    Row fRow = sheet.getRow(firstRow);
                    Cell fCell = fRow.getCell(firstColumn);
                    return getCellValue(fCell);
                }
            }
        }

        return null;
    }


    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    @Override
    public LayuiPageInfo huopeiList(Huopei huopei, String timeLimit) {
        Page pageContext = getPageContext();
        IPage page = huopeiMapper.huopeiList(pageContext, huopei, timeLimit);
//        List<Huopei> list = huopeiMapper.huopeiList(huopei, timeLimit);
//        return list;
        return LayuiPageFactory.createPageInfo(page);
    }

    @Override
    public Huopei getByShopCode(String shopCode, Date beginTime) {
        return huopeiMapper.getByShopCode(shopCode, beginTime);
    }

    /**
     * 导出excel
     * @param request
     * @param response
     * @param shopName
     * @param beginTime
     * @param shopCode
     * @param date
     * @return
     */
    @Override
    public ResponseEntity<byte[]> exportExcel(HttpServletRequest request, HttpServletResponse response,
                                              String shopName, Date beginTime, String shopCode, String date) {

//        String startTime;
//        String endTime;
//        Date start = null;
//        Date end = null;
        Huopei huopei = new Huopei();
//
//        if (ToolUtil.isNotEmpty(date)) {
//            String[] split = date.split(" - ");
//            startTime = split[0] + "-01";
//            endTime = split[1] + "-01";
//            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
//
//            try {
//                start = format.parse(startTime);
//                end = format.parse(endTime);
//            } catch (ParseException e) {
//                e.printStackTrace();
//            }
//
//            huopei.setBeginTime(start);
//            huopei.setEndTime(end);
//
//        }else {
//            huopei.setBeginTime(beginTime);
//        }

        try {
            logger.info(">>>>>>>>>>开始导出excel>>>>>>>>>>");

            //TODO-1 要导出的数据内容

            huopei.setBeginTime(beginTime);
            huopei.setShopName(shopName);
            huopei.setShopCode(shopCode);

            //获取所有时间段
            List<Huopei> timeList = huopeiMapper.exportTime(huopei, date);

            //要导出的list
//            List<Huopei> list = getHuopei(huopei,date);
            List<Huopei> list = exportHuopei(huopei,date);
            BaseFrontController baseFrontController = new BaseFrontController();

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


            if (timeList.size() > 1){
                //文件名称
                String begin = sdf.format(timeList.get(0).getBeginTime());
                String begin1 = sdf.format(timeList.get(timeList.size()-1).getBeginTime());
                String time = begin.split("-")[1];
                String time1 = begin1.split("-")[1];
                String name = time + "月-" + time1 + "月货赔表";

                return baseFrontController.buildResponseEntity(export(list, timeList), name + ".xls");

            }else if (timeList.size() == 1){
                //文件名称
                String begin = sdf.format(list.get(0).getBeginTime());
                String time = begin.split("-")[1];
                String name = time + "月货赔表";
                return baseFrontController.buildResponseEntity(export(list, timeList), name + ".xls");

            } else {
                return baseFrontController.buildResponseEntity(null, null + ".xls");
            }


        } catch (Exception e) {
            e.printStackTrace();
            logger.error(">>>>>>>>>>导出excel 异常，原因为：" + e.getMessage());
        }
        return null;
    }

    /**
     * 导出excel
     *
     * @param list
     * @return
     */
    private InputStream export(List<Huopei> list, List<Huopei> timeList) {
        logger.info(">>>>>>>>>>>>>>>>>>>>开始进入导出方法>>>>>>>>>>");
        ByteArrayOutputStream output = null;
        InputStream inputStream1 = null;
        SXSSFWorkbook wb = new SXSSFWorkbook(1000);// 保留1000条数据在内存中
        SXSSFSheet sheet = wb.createSheet();
        // 设置报表头样式
        CellStyle header = ExcelFormatUtil.headSytle(wb);// cell样式
        CellStyle content = ExcelFormatUtil.contentStyle(wb);// 报表体样式

        //TODO-2 每一列字段名
        String[] titles = new String[]{"", "门店编号", "门店名称", "品相类别名称", "品相编号", "品相名称", "规格", "单位",
                "非税单价", "理论耗用数量", "实际耗用数量", "耗用数量分差", "耗用金额分差", "加汤等", "金额", "营业额",
                "营业额万分之五", "营业额万分之十"};

        // 字段名所在表格的宽度，数量应与列字段名数量一致
        int[] ints = new int[]{1000, 3000, 5000, 5000, 3000, 5000, 5000, 3000, 3000, 3000, 3000, 3000, 3000, 3000, 3000, 3000, 3000, 3000};

        //TODO-3 设置总标题内容，没有可略过
        SXSSFRow row1 = sheet.createRow(0);
        SXSSFCell cell0 = row1.createCell(0);

        //合并单元格
        CellRangeAddress regionFist = new CellRangeAddress(0, 0, 0, 17); //设置第一行标题：指定 4 个参数，起始行，结束行，起始列，结束列,
        sheet.addMergedRegion(regionFist);
        //设置每一列的字段名

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String begin = sdf.format(timeList.get(0).getBeginTime());
        String end = sdf.format(timeList.get(timeList.size() - 1).getEndTime());

        cell0.setCellValue("档口原料用量差异分析-货赔 (业务日期:" + begin + " 至 " + end + ")");
        cell0.setCellStyle(header);

        CellStyle cellStyle = wb.createCellStyle();
        cellStyle.setBorderBottom(BorderStyle.THIN);
        cellStyle.setBorderLeft(BorderStyle.THIN);
        cellStyle.setBorderRight(BorderStyle.THIN);
        cellStyle.setBorderTop(BorderStyle.THIN);
        cellStyle.setWrapText(true);// 设置自动换行
        cellStyle.setAlignment(HorizontalAlignment.CENTER);// 设置单元格字体显示居中（左右方向）
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);// 设置单元格字体显示居中(上下方向)
        //设置单元格背景颜色
        cellStyle.setFillPattern(FillPatternType.BIG_SPOTS);
        cellStyle.setFillForegroundColor(IndexedColors.RED.getIndex());
        cellStyle.setFillBackgroundColor(IndexedColors.RED.getIndex());


        //TODO-4 设置内容标题
        //内容的标题所在行
        int concentitleStartRow = 2;
        //设置表头样式
        ExcelFormatUtil.initContentTitleEX(sheet, header, concentitleStartRow, titles, ints);
        logger.info(">>>>>>>>>>>>>>>>>>>>表头样式设置完成>>>>>>>>>>");

        //TODO-5 从第contentStartRow行开始为内容数据
        int contentStartRow = 3;

        if (list != null && list.size() > 0) {
            logger.info(">>>>>>>>>>>>>>>>>>>>开始遍历数据组装单元格内容>>>>>>>>>>");

            int p = 0;
                for (int i = 0; i < list.size(); i++) {

                    if (list.get(i).getNum() != null && list.get(i).getNum().equals("0")){

                        //合并单元格
                        CellRangeAddress region = new CellRangeAddress(contentStartRow + i - 1, contentStartRow + i - 1, 0, 17); //设置第一行标题：指定 4 个参数，起始行，结束行，起始列，结束列,
                        sheet.addMergedRegion(region);
                        SXSSFRow row2 = sheet.createRow(contentStartRow + i - 1);
                        SXSSFCell cell2 = row2.createCell(0);


                        int ij = p++;
                        Date beginTime = timeList.get(ij).getBeginTime();
                        Date endTime = timeList.get(ij).getEndTime();
                        String begin1 = sdf.format(beginTime);
                        String end1 = sdf.format(endTime);
                        cell2.setCellValue("档口原料用量差异分析-货赔 (业务日期:" + begin1 + " 至 " + end1 + ")");

                        cell2.setCellStyle(header);
                        cell2.setCellStyle(cellStyle);
                    }
                    Huopei huopei = list.get(i);

                    SXSSFRow row = sheet.createRow(contentStartRow + i);
                    int j = 0;

                    //序号
                    SXSSFCell cell = row.createCell(j++);
                    cell.setCellValue(huopei.getNum());
                    cell.setCellStyle(content);

                    // 门店编号
                    cell = row.createCell(j++);
                    cell.setCellValue(huopei.getShopCode());
                    cell.setCellStyle(content);

                    // 门店名称
                    cell = row.createCell(j++);
                    cell.setCellValue(huopei.getShopName());
                    cell.setCellStyle(content);

                    // 品项类别名称
                    cell = row.createCell(j++);
                    cell.setCellValue(huopei.getClassName());
                    cell.setCellStyle(content);

                    // 品项编号
                    cell = row.createCell(j++);
                    cell.setCellValue(huopei.getProCode());
                    cell.setCellStyle(content);

                    // 品项名称
                    cell = row.createCell(j++);
                    cell.setCellValue(huopei.getProName());
                    cell.setCellStyle(content);

                    // 规格
                    cell = row.createCell(j++);
                    cell.setCellValue(huopei.getSpec());
                    cell.setCellStyle(content);

                    // 单位
                    cell = row.createCell(j++);
                    cell.setCellValue(huopei.getUnit());
                    cell.setCellStyle(content);

                    //非税单价
                    cell = row.createCell(j++);
                    cell.setCellValue(huopei.getPrice());
                    cell.setCellStyle(content);

                    //理论耗用数量
                    cell = row.createCell(j++);
                    cell.setCellValue(huopei.getThNum() == null ? "0" : huopei.getThNum().toString());
                    cell.setCellStyle(content);

                    //实际耗用数量
                    cell = row.createCell(j++);
                    cell.setCellValue(huopei.getRealNum() == null ? "0" : huopei.getRealNum().toString());
                    cell.setCellStyle(content);

                    //耗用数量分差
                    cell = row.createCell(j++);
                    cell.setCellValue(huopei.getNumTotal());
                    cell.setCellStyle(content);

                    //耗用金额分差
                    cell = row.createCell(j++);
                    cell.setCellValue(huopei.getAmountTotal());
                    cell.setCellStyle(content);

                    //加汤等
                    cell = row.createCell(j++);
                    cell.setCellValue(huopei.getSoup());
                    cell.setCellStyle(content);

                    //金额
                    cell = row.createCell(j++);
                    cell.setCellValue(huopei.getSoupAmount() == null ? "" : huopei.getSoupAmount().toString());
                    cell.setCellStyle(content);

                    //营业额
                    cell = row.createCell(j++);
                    cell.setCellValue(huopei.getTurnover() == null ? null : huopei.getTurnover().toString());
                    cell.setCellStyle(content);

                    //营业额万分之五
                    cell = row.createCell(j++);
                    cell.setCellValue(huopei.getFive() == null ? null : huopei.getFive().toString());
                    cell.setCellStyle(content);

                    //营业额万分之十
                    cell = row.createCell(j++);
                    cell.setCellValue(huopei.getTen() == null ? null : huopei.getTen().toString());
                    cell.setCellStyle(content);

                }

            logger.info(">>>>>>>>>>>>>>>>>>>>结束遍历数据组装单元格内容>>>>>>>>>>");
        }

        try {
            output = new ByteArrayOutputStream();
            wb.write(output);
            inputStream1 = new ByteArrayInputStream(output.toByteArray());
            output.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            try {
                if (output != null) {
                    output.close();
                    if (inputStream1 != null) {
                        inputStream1.close();
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return inputStream1;
    }

    /**
     * 导出时货赔列表
     * @param param
     * @param date
     * @return
     */
    public List<Huopei> exportHuopei(Huopei param, String date) {

        List<Huopei> huopeiList = new ArrayList<>();//获取该店的货赔信息
        List<Huopei> className = new ArrayList<>();//查询该店的品相类别
        List<Huopei> timeList = new ArrayList<>();//获取所有时间段

        //如果导出时没有选择店名
        if (ToolUtil.isEmpty(param.getShopCode()) && ToolUtil.isEmpty(param.getShopName())){

            //当前登陆者姓名
            String name = LoginContextHolder.getContext().getUser().getName();
            //当前登陆者角色
            List<String> roleNames = LoginContextHolder.getContext().getUser().getRoleNames();

            //会计
            if (roleNames.contains("会计")){
                //查询该会计名下的所有店铺
                List<String> dmList = dmList(name);
                //获取该店的货赔信息
                huopeiList = huopeiMapper.hpList(dmList, date);
                //查询该店的品相类别
                className = huopeiMapper.nameList(dmList);
                //获取所有时间段
                timeList = huopeiMapper.timeList(dmList, date);

                //店长
            }else if(roleNames.contains("店长报销单管理")){
                //查询店长的店铺
                List dzList = dzList(name);

                //获取该店的货赔信息
                huopeiList = huopeiMapper.hpList(dzList, date);
                //查询该店的品相类别
                className = huopeiMapper.nameList(dzList);
                //获取所有时间段
                timeList = huopeiMapper.timeList(dzList, date);

            }else if (roleNames.contains("超级管理员") || roleNames.contains("人事") || roleNames.contains("财务主管")){
                //获取该店的货赔信息
                huopeiList = huopeiMapper.getExport(param, date);
                //查询该店的品相类别
                className = huopeiMapper.exportClass(param);
                //获取所有时间段
                timeList = huopeiMapper.exportTime(param, date);
            }
        }else {
            //获取该店的货赔信息
            huopeiList = huopeiMapper.getExport(param, date);
            //查询该店的品相类别
            className = huopeiMapper.exportClass(param);
            //获取所有时间段
            timeList = huopeiMapper.exportTime(param, date);
        }






        //要导出的list
        List<Huopei> list = new ArrayList<>();

//        //获取该店的货赔信息
//        List<Huopei> huopeiList = huopeiMapper.getExport(param, date);
//        //查询该店的品相类别
//        List<Huopei> className = huopeiMapper.exportClass(param);
//        //获取所有时间段
//        List<Huopei> timeList = huopeiMapper.exportTime(param, date);

        if (CollectionUtil.isNotEmpty(timeList)){
            for (Huopei time : timeList) {

                BigDecimal suma = new BigDecimal(0);
                BigDecimal sumb = new BigDecimal(0);
                BigDecimal sumc = new BigDecimal(0);
                BigDecimal sumd = new BigDecimal(0);
                BigDecimal sume = new BigDecimal(0);

                if (CollectionUtil.isNotEmpty(className)) {
                    //循环该店品相类别
                    for (Huopei name : className) {
                        if (name.getBeginTime().equals(time.getBeginTime()) && name.getShopCode().equals(time.getShopCode())){

                            BigDecimal sum1 = new BigDecimal(0);
                            BigDecimal sum2 = new BigDecimal(0);
                            BigDecimal sum3 = new BigDecimal(0);
                            BigDecimal sum4 = new BigDecimal(0);
                            BigDecimal sum5 = new BigDecimal(0);

                            if (CollectionUtil.isNotEmpty(huopeiList)) {
                                //循环该店货赔信息
                                for (Huopei huopei : huopeiList) {
                                    //品相类别相同,店相同
                                    if (name.getClassName().equals(huopei.getClassName()) && time.getBeginTime().equals(huopei.getBeginTime())
                                    && huopei.getShopCode().equals(time.getShopCode())) {

                                        sum1 = sum1.add(huopei.getThNum() == null ? BigDecimal.ZERO : new BigDecimal(huopei.getThNum()));
                                        sum2 = sum2.add(huopei.getRealNum() == null ? BigDecimal.ZERO : new BigDecimal(huopei.getRealNum()));
                                        sum3 = sum3.add(huopei.getNumTotal() == null ? BigDecimal.ZERO : new BigDecimal(huopei.getNumTotal()));
                                        sum4 = sum4.add(huopei.getAmountTotal() == null ? BigDecimal.ZERO : new BigDecimal(huopei.getAmountTotal()));
                                        sum5 = sum5.add(huopei.getSoupAmount() == null ? BigDecimal.ZERO : huopei.getSoupAmount());

                                        list.add(huopei);
                                    }
                                }
                            }
                            name.setNum("小计");
                            name.setThNum(String.valueOf(sum1));//理论耗用数量
                            name.setRealNum(String.valueOf(sum2));//实际耗用数量
                            name.setNumTotal(String.valueOf(sum3));//耗用数量分差
                            name.setAmountTotal(String.valueOf(sum4));//耗用金额分差
                            name.setSoupAmount(sum5);//加汤金额
                            list.add(name);

                            suma = suma.add(sum1);//理论耗用数量
                            sumb = sumb.add(sum2);//实际耗用数量
                            sumc = sumc.add(sum3);//耗用数量分差
                            sumd = sumd.add(sum4);//耗用金额分差
                            sume = sume.add(sum5);//加汤金额
                        }

                    }
                }

                String shopCode = null;
                if (param.getShopCode() != null) {
                    shopCode = param.getShopCode();
                } else if (huopeiList.size() != 0){
                    shopCode = time.getShopCode();
                }
                if (shopCode != null){

                    //查询该店的盘亏信息
                    CaiwuPankui pankui = pankuiMapper.getPankui(shopCode, time.getBeginTime());

                    Huopei huopei = new Huopei();
                    huopei.setNum("总计");
                    huopei.setThNum(String.valueOf(suma));//理论耗用数量
                    huopei.setRealNum(String.valueOf(sumb));//实际耗用数量
                    huopei.setNumTotal(String.valueOf(sumc));//耗用数量分差
                    huopei.setAmountTotal(String.valueOf(sumd));//耗用金额分差
                    huopei.setSoupAmount(sume);//加汤金额
                    huopei.setBeginTime(time.getBeginTime());
                    huopei.setEndTime(time.getEndTime());
                    list.add(huopei);

                    Huopei result = new Huopei();
                    result.setShopCode(shopCode);
                    result.setShopName("餐具盘亏");
                    result.setClassName(pankui.getCjPk() == null ? "0" : pankui.getCjPk());
                    result.setProCode("免赔");
                    result.setProName(pankui.getCjMp() == null ? "0" : pankui.getCjMp());
                    result.setSpec("其他免赔(加汤等)");
                    result.setUnit(pankui.getCjSoup() == null ? "0" : pankui.getCjSoup());
                    result.setPrice("餐具货赔");
                    result.setThNum(pankui.getCjHp() == null ? "0" : pankui.getCjHp());
                    result.setBeginTime(time.getBeginTime());
                    result.setEndTime(time.getEndTime());
                    list.add(result);

                    Huopei result1 = new Huopei();
                    result1.setShopCode(shopCode);
                    result1.setShopName("清江鱼盘亏");
                    result1.setClassName(pankui.getQjyPk() == null ? "0" : pankui.getQjyPk());
                    result1.setProCode("免赔");
                    result1.setProName(pankui.getQjyMp() == null ? "0" : pankui.getQjyMp());
                    result1.setSpec("其他免赔(加汤等)");
                    result1.setUnit(pankui.getQjySoup() == null ? "0" : pankui.getQjySoup());
                    result1.setPrice("清江鱼货赔");
                    result1.setThNum(pankui.getQjyHp() == null ? "0" : pankui.getQjyHp());
                    result1.setBeginTime(time.getBeginTime());
                    result1.setEndTime(time.getEndTime());
                    list.add(result1);

                    Huopei result2 = new Huopei();
                    result2.setShopCode(shopCode);
                    result2.setShopName("酱料盘亏");
                    result2.setClassName(pankui.getJlPk() == null ? "0" : pankui.getJlPk());
                    result2.setProCode("免赔");
                    result2.setProName(pankui.getJlMp() == null ? "0" : pankui.getJlMp());
                    result2.setSpec("其他免赔(加汤等)");
                    result2.setUnit(pankui.getJlSoup() == null ? "0" : pankui.getJlSoup());
                    result2.setPrice("酱料货赔");
                    result2.setThNum(pankui.getJlHp() == null ? "0" : pankui.getJlHp());
                    result2.setBeginTime(time.getBeginTime());
                    result2.setEndTime(time.getEndTime());
                    list.add(result2);

                    Huopei result3 = new Huopei();
                    result3.setShopCode(shopCode);
                    result3.setShopName("酒水盘亏");
                    result3.setClassName(pankui.getJsPk() == null ? "0" : pankui.getJsPk());
                    result3.setProCode("免赔");
                    result3.setProName(pankui.getJsMp() == null ? "0" : pankui.getJsMp());
                    result3.setSpec("其他免赔(加汤等)");
                    result3.setUnit(pankui.getJsSoup() == null ? "0" : pankui.getJsSoup());
                    result3.setPrice("酒水货赔");
                    result3.setThNum(pankui.getJsHp() == null ? "0" : pankui.getJsHp());
                    result3.setBeginTime(time.getBeginTime());
                    result3.setEndTime(time.getEndTime());
                    list.add(result3);

                    String pbKc = pankui.getPbKc() == null ? "0" : pankui.getPbKc();
                    String pbPd = pankui.getPbPd() == null ? "0" : pankui.getPbPd();

                    Huopei result4 = new Huopei();
                    result4.setShopCode(shopCode);
                    result4.setShopName("平板电脑应有库存");
                    result4.setClassName(pbKc);
                    result4.setProCode("平板电脑盘点");
                    result4.setProName(pbPd);

                    result4.setPrice("平板货赔");
                    result4.setThNum(pankui.getPbHp() == null ? "0" : pankui.getPbHp());
                    result4.setNumTotal("合计");
                    result4.setAmountTotal(pankui.getHeji() == null ? "0" : pankui.getHeji());
                    result4.setBeginTime(time.getBeginTime());
                    result4.setEndTime(time.getEndTime());
                    list.add(result4);

                    Huopei huopei1 = new Huopei();
                    list.add(huopei1);
                }
            }
        }

        return list;
    }



    /**
     * 货赔表详细
     *
     * @param param
     * @return
     */
    @Override
    public List<Huopei> getHuopei(Huopei param, String date) {
        //要导出的list
        List<Huopei> list = new ArrayList<>();

        //获取该店的货赔信息
        List<Huopei> huopeiList = huopeiMapper.getHuopei(param,date);
        //查询该店的品相类别
        List<Huopei> className = huopeiMapper.selectClassName(param);
        //获取所有时间段
        List<Huopei> timeList = huopeiMapper.selectTime(param, date);

        if (CollectionUtil.isNotEmpty(timeList)){
            for (Huopei time : timeList) {
                int i = 0;

                double five = 0;
                double ten = 0;

                BigDecimal suma = new BigDecimal(0);
                BigDecimal sumb = new BigDecimal(0);
                BigDecimal sumc = new BigDecimal(0);
                BigDecimal sumd = new BigDecimal(0);
                BigDecimal sume = new BigDecimal(0);

                Map<String, String> map = new HashMap();


                if (CollectionUtil.isNotEmpty(className)) {
                    //循环该店品相类别
                    for (Huopei name : className) {
                        //循环的时间相同
                        if (name.getBeginTime().equals(time.getBeginTime()) && name.getShopCode().equals(time.getShopCode())){

                            BigDecimal sum1 = new BigDecimal(0);
                            BigDecimal sum2 = new BigDecimal(0);
                            BigDecimal sum3 = new BigDecimal(0);
                            BigDecimal sum4 = new BigDecimal(0);
                            BigDecimal sum5 = new BigDecimal(0);

                            if (CollectionUtil.isNotEmpty(huopeiList)) {
                                //循环该店货赔信息
                                for (Huopei huopei : huopeiList) {
                                    //品相类别相同
                                    if (name.getClassName().equals(huopei.getClassName()) && time.getBeginTime().equals(huopei.getBeginTime())) {

                                        huopei.setNum(String.valueOf(i++));
                                        huopeiMapper.updateNum(huopei.getNum(), huopei.getShopCode(), huopei.getProCode(), huopei.getBeginTime());

                                        sum1 = sum1.add(huopei.getThNum() == null ? BigDecimal.ZERO : new BigDecimal(huopei.getThNum()));
                                        sum2 = sum2.add(huopei.getRealNum() == null ? BigDecimal.ZERO : new BigDecimal(huopei.getRealNum()));
                                        sum3 = sum3.add(huopei.getNumTotal() == null ? BigDecimal.ZERO : new BigDecimal(huopei.getNumTotal()));
                                        sum4 = sum4.add(huopei.getAmountTotal() == null ? BigDecimal.ZERO : new BigDecimal(huopei.getAmountTotal()));
                                        sum5 = sum5.add(huopei.getSoupAmount() == null ? BigDecimal.ZERO : huopei.getSoupAmount());

                                        list.add(huopei);

                                        five = huopei.getFive() == null ? 0 : huopei.getFive().doubleValue();//营业额万分之五
                                        ten = huopei.getTen() == null ? 0 : huopei.getTen().doubleValue();//营业额万分之十
                                    }
                                }
                            }
                            name.setNum("小计");
                            name.setThNum(String.valueOf(sum1));//理论耗用数量
                            name.setRealNum(String.valueOf(sum2));//实际耗用数量
                            name.setNumTotal(String.valueOf(sum3));//耗用数量分差
                            name.setAmountTotal(String.valueOf(sum4));//耗用金额分差
                            name.setSoupAmount(sum5);//加汤金额
                            list.add(name);

                            //修改数据库各小计
                            Huopei huopei = new Huopei();
                            if (name.getClassName().equals("餐具（实收资本）")) {
                                huopei.setCjAmSum(String.valueOf(sum4));//餐具耗用金额分差小计
                                huopei.setCjNumSum(String.valueOf(sum3));//餐具耗用数量分差小计
                                huopei.setCjSoup(String.valueOf(sum5));//餐具加汤小计

                                int cjAmSum = Double.valueOf(huopei.getCjAmSum()).intValue();//转换成int
                                int cjNumSum = Double.valueOf(huopei.getCjNumSum()).intValue();//转换成int

                                if (huopei.getCjAmSum() != null && cjAmSum < 0) {
//                        map.put("cjPk",huopei.getCjAmSum() == null ? "0" : String.valueOf(Math.abs(Math.round(Double.valueOf(huopei.getCjAmSum())))));
                                    map.put("cjPk", String.valueOf(Math.abs(Math.round(Double.valueOf(huopei.getCjAmSum())))));
                                } else {
                                    map.put("cjPk", "0");
                                }
                                map.put("cjSoup",String.valueOf(Math.round(Double.valueOf(huopei.getCjSoup()))));
                            } else if (name.getClassName().equals("冻货")) {
                                huopei.setDhAmSum(String.valueOf(sum4));//冻货耗用金额分差小计
                                huopei.setDhNumSum(String.valueOf(sum3));//冻货耗用数量分差小计
                                huopei.setDhSoup(String.valueOf(sum5));//冻货加汤小计

                                int dhAmSum = Double.valueOf(huopei.getDhAmSum()).intValue();//转换成int

                                if (huopei.getDhAmSum() != null && dhAmSum < 0) {
//                        map.put("qjyPk",huopei.getDhAmSum() == null ? "0" : String.valueOf(Math.abs(Math.round(Double.valueOf(huopei.getDhAmSum())))));
                                    map.put("qjyPk", String.valueOf(Math.abs(Math.round(Double.valueOf(huopei.getDhAmSum())))));
                                } else {
                                    map.put("qjyPk", "0");
                                }
                                map.put("qjySoup",String.valueOf(Math.round(Double.valueOf(huopei.getDhSoup()))));
                            } else if (name.getClassName().equals("酱料")) {
                                huopei.setJlAmSum(String.valueOf(sum4));//酱料耗用金额分差小计
                                huopei.setJlNumSum(String.valueOf(sum3));//酱料耗用数量分差小计
                                huopei.setJlSoup(String.valueOf(sum5));//酱料加汤小计

                                int jlAmSum = Double.valueOf(huopei.getJlAmSum()).intValue();//转换成int

                                if (huopei.getJlAmSum() != null && jlAmSum < 0) {
//                        map.put("jlPk",huopei.getJlAmSum() == null ? "0" : String.valueOf(Math.abs(Math.round(Double.valueOf(huopei.getJlAmSum())))));
                                    map.put("jlPk", String.valueOf(Math.abs(Math.round(Double.valueOf(huopei.getJlAmSum())))));
                                } else {
                                    map.put("jlPk", "0");
                                }
                                map.put("jlSoup",String.valueOf(Math.round(Double.valueOf(huopei.getJlSoup()))));
                            } else if (name.getClassName().equals("酒水")) {
                                huopei.setJsAmSum(String.valueOf(sum4));//酒水耗用金额分差小计
                                huopei.setJsNumSum(String.valueOf(sum3));//酒水耗用数量分差小计
                                huopei.setJsSoup(String.valueOf(sum5));//酒水加汤小计

                                int jsAmSum = Double.valueOf(huopei.getJsAmSum()).intValue();//转换成int

                                if (huopei.getJsAmSum() != null && jsAmSum < 0) {
//                        map.put("jsPk",huopei.getJsAmSum() == null ? "0" : String.valueOf(Math.abs(Math.round(Double.valueOf(huopei.getJsAmSum())))));
                                    map.put("jsPk", String.valueOf(Math.abs(Math.round(Double.valueOf(huopei.getJsAmSum())))));
                                } else {
                                    map.put("jsPk", "0");
                                }
                                map.put("jsSoup",String.valueOf(Math.round(Double.valueOf(huopei.getJsSoup()))));
                            }

                            if (param.getShopCode() != null) {
                                huopei.setShopCode(param.getShopCode());
                            } else if (huopeiList.size() != 0){
                                huopei.setShopCode(huopeiList.get(0).getShopCode());
                            }
                            huopei.setBeginTime(name.getBeginTime());

                            huopeiMapper.update(huopei);

                            suma = suma.add(sum1);//理论耗用数量
                            sumb = sumb.add(sum2);//实际耗用数量
                            sumc = sumc.add(sum3);//耗用数量分差
                            sumd = sumd.add(sum4);//耗用金额分差
                            sume = sume.add(sum5);//加汤金额
                        }

                    }
                }

                String shopCode = null;
                if (param.getShopCode() != null) {
                    shopCode = param.getShopCode();
                } else if (huopeiList.size() != 0){
                    shopCode = huopeiList.get(0).getShopCode();
                }
                if (shopCode != null){
                    //盘亏表新增相关数据
                    int count = pankuiMapper.count(shopCode, time.getBeginTime());

                    if (count == 0) {
                        CaiwuPankui pankui1 = new CaiwuPankui();
                        pankui1.setShopCode(shopCode);
                        pankui1.setCjPk(map.get("cjPk"));//餐具盘亏
                        pankui1.setQjyPk(map.get("qjyPk"));//清江鱼盘亏
                        pankui1.setJlPk(map.get("jlPk"));//酱料盘亏
                        pankui1.setJsPk(map.get("jsPk"));//酒水盘亏
                        pankui1.setCjMp(String.valueOf(Math.round(ten)));//餐具免赔
                        pankui1.setQjyMp(String.valueOf(Math.round(five)));//清江鱼免赔
                        pankui1.setJlMp(String.valueOf(Math.round(five)));//酱料免赔
                        pankui1.setJsMp("0");//酒水免赔
                        pankui1.setPbKc("0");//平板库存
                        pankui1.setPbPd("0");//平板盘点
                        pankui1.setBeginTime(time.getBeginTime());//开始时间
                        pankui1.setEndTime(time.getEndTime());//结束时间

                        pankuiMapper.insert(pankui1);


                    }
                    //查询该店的盘亏信息
                    CaiwuPankui pankui = pankuiMapper.getPankui(shopCode, time.getBeginTime());

//                    //修改加汤免赔，货赔
//                    if (count != 0){
//
//                        CaiwuPankui pankui2 = new CaiwuPankui();
//
//                        pankui2.setShopCode(shopCode);
//                        pankui2.setBeginTime(time.getBeginTime());
//
//                        if (pankui.getCjSoup() == null || pankui.getCjSoup().equals("0")){
//                            pankui2.setCjSoup(map.get("cjSoup"));//餐具加汤
//
//                        }else if (pankui.getQjySoup() == null || pankui.getQjySoup().equals("0")){
//                            pankui2.setQjySoup(map.get("qjySoup"));//清江鱼加汤
//
//                        }else if (pankui.getJlSoup() == null || pankui.getJlSoup().equals("0")){
//                            pankui2.setJlSoup(map.get("jsSoup"));//酱料加汤
//
//                        }else if (pankui.getJsSoup() == null || pankui.getJsSoup().equals("0")){
//                            pankui2.setJsSoup(map.get("jsSoup"));//酒水加汤
//
//                        }
//
//
//                        //酒水
//                        BigDecimal jsMp = pankui.getJsMp() == null ? BigDecimal.ZERO : new BigDecimal(pankui.getJsMp());
//                        BigDecimal jsSoup = pankui.getJsSoup() == null ? BigDecimal.ZERO : new BigDecimal(pankui.getJsSoup());
//                        BigDecimal jsPk = pankui.getJsPk() == null ? BigDecimal.ZERO : new BigDecimal(pankui.getJsPk());
//                        //酱料
//                        BigDecimal jlMp = pankui.getJlMp() == null ? BigDecimal.ZERO : new BigDecimal(pankui.getJlMp());
//                        BigDecimal jlSoup = pankui.getJlSoup() == null ? BigDecimal.ZERO : new BigDecimal(pankui.getJlSoup());
//                        BigDecimal jlPk = pankui.getJlPk() == null ? BigDecimal.ZERO : new BigDecimal(pankui.getJlPk());
//
//                        //清江鱼
//                        BigDecimal qjyMp = pankui.getQjyMp() == null ? BigDecimal.ZERO : new BigDecimal(pankui.getQjyMp());
//                        BigDecimal qjySoup = pankui.getQjySoup() == null ? BigDecimal.ZERO : new BigDecimal(pankui.getQjySoup());
//                        BigDecimal qjyPk = pankui.getQjyPk() == null ? BigDecimal.ZERO : new BigDecimal(pankui.getQjyPk());
//
//                        //餐具
//                        BigDecimal cjMp = pankui.getCjMp() == null ? BigDecimal.ZERO : new BigDecimal(pankui.getCjMp());
//                        BigDecimal cjSoup = pankui.getCjSoup() == null ? BigDecimal.ZERO : new BigDecimal(pankui.getCjSoup());
//                        BigDecimal cjPk = pankui.getCjPk() == null ? BigDecimal.ZERO : new BigDecimal(pankui.getCjPk());
//
//
//                        //免赔和 >= 盘亏
//                        if (jsMp.add(jsSoup).compareTo(jsPk) > -1){
//                            pankui2.setJsHp("0");
//                        }else {
//                            pankui2.setJsHp(String.valueOf(jsPk.subtract(jsMp.add(jsSoup))));
//                        }
//
//                        if (jlMp.add(jlSoup).compareTo(jlPk) > -1){
//                            pankui2.setJlHp("0");
//                        }else {
//                            pankui2.setJlHp(String.valueOf(jlPk.subtract(jlMp.add(jlSoup))));
//                        }
//
//                        if (qjyMp.add(qjySoup).compareTo(qjyPk) > -1){
//                            pankui2.setQjyHp("0");
//                        }else {
//                            pankui2.setQjyHp(String.valueOf(qjyPk.subtract(qjyMp.add(qjySoup))));
//                        }
//
//                        if (cjMp.add(cjSoup).compareTo(cjPk) > -1){
//                            pankui2.setCjHp("0");
//                        }else {
//                            pankui2.setCjHp(String.valueOf(cjPk.subtract(cjMp.add(cjSoup))));
//                        }
//
//                        pankuiMapper.update(pankui2);
//
//                    }

                    Huopei huopei = new Huopei();
                    huopei.setNum("总计");
                    huopei.setThNum(String.valueOf(suma));//理论耗用数量
                    huopei.setRealNum(String.valueOf(sumb));//实际耗用数量
                    huopei.setNumTotal(String.valueOf(sumc));//耗用数量分差
                    huopei.setAmountTotal(String.valueOf(sumd));//耗用金额分差
                    huopei.setSoupAmount(sume);//加汤金额
                    list.add(huopei);

                    //编辑数据库总计
                    Huopei hp = new Huopei();
                    hp.setNumZongji(String.valueOf(sumc));//耗用数量分差总计
                    hp.setAmZongji(String.valueOf(sumd));//耗用金额分差总计
                    hp.setSoupSum(String.valueOf(sume));//加汤总计
                    hp.setShopCode(shopCode);//门店编号
                    hp.setBeginTime(time.getBeginTime());
                    huopeiMapper.update(hp);


                    Huopei result = new Huopei();
                    result.setShopCode(shopCode);
                    result.setShopName("餐具盘亏");
                    result.setClassName(pankui.getCjPk() == null ? "0" : pankui.getCjPk());
                    result.setProCode("免赔");
                    result.setProName(pankui.getCjMp() == null ? "0" : pankui.getCjMp());
                    result.setSpec("其他免赔(加汤等)");
                    result.setUnit(pankui.getCjSoup() == null ? "0" : pankui.getCjSoup());
                    result.setPrice("餐具货赔");
                    result.setThNum(pankui.getCjHp() == null ? "0" : pankui.getCjHp());
                    result.setBeginTime(time.getBeginTime());
                    result.setEndTime(time.getEndTime());
                    list.add(result);

                    Huopei result1 = new Huopei();
                    result1.setShopCode(shopCode);
                    result1.setShopName("清江鱼盘亏");
                    result1.setClassName(pankui.getQjyPk() == null ? "0" : pankui.getQjyPk());
                    result1.setProCode("免赔");
                    result1.setProName(pankui.getQjyMp() == null ? "0" : pankui.getQjyMp());
                    result1.setSpec("其他免赔(加汤等)");
                    result1.setUnit(pankui.getQjySoup() == null ? "0" : pankui.getQjySoup());
                    result1.setPrice("清江鱼货赔");
                    result1.setThNum(pankui.getQjyHp() == null ? "0" : pankui.getQjyHp());
                    result1.setBeginTime(time.getBeginTime());
                    result1.setEndTime(time.getEndTime());
                    list.add(result1);

                    Huopei result2 = new Huopei();
                    result2.setShopCode(shopCode);
                    result2.setShopName("酱料盘亏");
                    result2.setClassName(pankui.getJlPk() == null ? "0" : pankui.getJlPk());
                    result2.setProCode("免赔");
                    result2.setProName(pankui.getJlMp() == null ? "0" : pankui.getJlMp());
                    result2.setSpec("其他免赔(加汤等)");
                    result2.setUnit(pankui.getJlSoup() == null ? "0" : pankui.getJlSoup());
                    result2.setPrice("酱料货赔");
                    result2.setThNum(pankui.getJlHp() == null ? "0" : pankui.getJlHp());
                    result2.setBeginTime(time.getBeginTime());
                    result2.setEndTime(time.getEndTime());
                    list.add(result2);

                    Huopei result3 = new Huopei();
                    result3.setShopCode(shopCode);
                    result3.setShopName("酒水盘亏");
                    result3.setClassName(pankui.getJsPk() == null ? "0" : pankui.getJsPk());
                    result3.setProCode("免赔");
                    result3.setProName(pankui.getJsMp() == null ? "0" : pankui.getJsMp());
                    result3.setSpec("其他免赔(加汤等)");
                    result3.setUnit(pankui.getJsSoup() == null ? "0" : pankui.getJsSoup());
                    result3.setPrice("酒水货赔");
                    result3.setThNum(pankui.getJsHp() == null ? "0" : pankui.getJsHp());
                    result3.setBeginTime(time.getBeginTime());
                    result3.setEndTime(time.getEndTime());
                    list.add(result3);


                    String pbKc = pankui.getPbKc() == null ? "0" : pankui.getPbKc();
                    String pbPd = pankui.getPbPd() == null ? "0" : pankui.getPbPd();

                    Huopei result4 = new Huopei();
                    result4.setShopCode(shopCode);
                    result4.setShopName("平板电脑应有库存");
                    result4.setClassName(pbKc);
                    result4.setProCode("平板电脑盘点");
                    result4.setProName(pbPd);

                    result4.setPrice("平板货赔");
                    result4.setThNum(pankui.getPbHp() == null ? "0" : pankui.getPbHp());
                    result4.setNumTotal("合计");
                    result4.setAmountTotal(pankui.getHeji() == null ? "0" : pankui.getHeji());
                    result4.setBeginTime(time.getBeginTime());
                    result4.setEndTime(time.getEndTime());
                    list.add(result4);

                    Huopei huopei1 = new Huopei();
                    list.add(huopei1);
                }
            }
        }


        return list;
    }



    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseData editHuopei(HuopeiDto huopeiDto) {
        Huopei huopei = new Huopei();

        CaiwuPankui pankui = new CaiwuPankui();

        //当前登陆者角色
        List<String> roleNames = LoginContextHolder.getContext().getUser().getRoleNames();
        int i = 0;

        //会计可以修改
        if (roleNames.contains("会计")) {

            //查询盘亏
            CaiwuPankui caiwuPankui = pankuiMapper.selectPankui(huopeiDto.getShopCode(),huopeiDto.getBeginTime());

            //货赔表对应数据
            Huopei hp = huopeiMapper.getByShopCode(huopeiDto.getShopCode(),huopeiDto.getBeginTime());

            //营业额
            if (huopeiDto.getTurnover() != null) {

                BigDecimal five = huopeiDto.getTurnover().multiply(new BigDecimal(0.0005));//营业额万分之五
                BigDecimal ten = huopeiDto.getTurnover().multiply(new BigDecimal(0.001));//营业额万分之十

                huopei.setFive(five);
                huopei.setTen(ten);
                huopei.setTurnover(huopeiDto.getTurnover());
                huopei.setShopCode(huopeiDto.getShopCode());
                huopei.setBeginTime(huopeiDto.getBeginTime());
                huopeiMapper.update(huopei);
                i = 1;

                String tenMp = huopei.getTen().setScale(0, BigDecimal.ROUND_HALF_UP).toString();
                String fiveMp = huopei.getFive().setScale(0, BigDecimal.ROUND_HALF_UP).toString();

                pankui.setCjMp(tenMp);//餐具免赔（万分之十）
                pankui.setQjyMp(fiveMp);//清江鱼免赔（万分之五）
                pankui.setJlMp(fiveMp);//酱料免赔（万分之五）

//                if (caiwuPankui.getCjMp().equals("0")) {
//                    pankui.setCjMp(tenMp);//餐具免赔（万分之十）
//                }
//                if (caiwuPankui.getQjyMp().equals("0")) {
//                    pankui.setQjyMp(fiveMp);//清江鱼免赔（万分之五）
//                }
//                if (caiwuPankui.getJsMp().equals("0")) {
//                    pankui.setJlMp(fiveMp);//酱料免赔（万分之五）
//                }
//                if (caiwuPankui.getJsMp() == "0"){
//                    pankui.setJsMp("0");//酒水免赔
//                }

            }
//            //加汤金额
//            else if (huopeiDto.getSoupAmount() != null){
//                pankui.setCjSoup(hp.getCjSoup());
//                pankui.setQjySoup(hp.getDhSoup());
//                pankui.setJlSoup(hp.getJlSoup());
//                pankui.setJsSoup(hp.getJsSoup());
//
//            }

            //加汤
            huopei.setSoup(huopeiDto.getSoup());
            //加汤金额
            huopei.setSoupAmount(huopeiDto.getSoupAmount());
            huopei.setShopCode(huopeiDto.getShopCode());
            huopei.setNum(huopeiDto.getNum());
            huopei.setBeginTime(huopeiDto.getBeginTime());
            huopeiMapper.updateHp(huopei);
            i = 2;


            //计算合计
            if (huopeiDto.getShopName() != null && huopeiDto.getShopName().equals("餐具盘亏")) {

                pankui.setCjPk(huopeiDto.getClassName());//餐具盘亏
                pankui.setCjMp(huopeiDto.getProName());//餐具免赔
                pankui.setCjSoup(huopeiDto.getUnit());//餐具加汤
                pankui.setCjHp(huopeiDto.getThNum());//餐具货赔
                huopeiDto.setCjHp(pankui.getCjHp());

                BigDecimal cjHp = pankui.getCjHp() == null ? new BigDecimal(0) : new BigDecimal(pankui.getCjHp());
                BigDecimal qjyHp = caiwuPankui.getQjyHp() == null ? new BigDecimal(0) : new BigDecimal(caiwuPankui.getQjyHp());
                BigDecimal jlHp = caiwuPankui.getJlHp() == null ? new BigDecimal(0) : new BigDecimal(caiwuPankui.getJlHp());
                BigDecimal jsHp = caiwuPankui.getJsHp() == null ? new BigDecimal(0) : new BigDecimal(caiwuPankui.getJsHp());
                BigDecimal pbHp = caiwuPankui.getPbHp() == null ? new BigDecimal(0) : new BigDecimal(caiwuPankui.getPbHp());
                BigDecimal heji = cjHp.add(qjyHp).add(jlHp).add(jsHp).add(pbHp);

                if (heji.compareTo(new BigDecimal(0)) != 0) {
                    pankui.setHeji(String.valueOf(heji));
                }

            } else if (huopeiDto.getShopName() != null && huopeiDto.getShopName().equals("清江鱼盘亏")) {

                pankui.setQjyPk(huopeiDto.getClassName());//清江鱼盘亏
                pankui.setQjyMp(huopeiDto.getProName());//清江鱼免赔
                pankui.setQjySoup(huopeiDto.getUnit());//清江鱼加汤
                pankui.setQjyHp(huopeiDto.getThNum());//清江鱼货赔
                huopeiDto.setQjyHp(pankui.getQjyHp());

                BigDecimal qjyHp = pankui.getQjyHp() == null ? new BigDecimal(0) : new BigDecimal(pankui.getQjyHp());
                BigDecimal cjHp = caiwuPankui.getCjHp() == null ? new BigDecimal(0) : new BigDecimal(caiwuPankui.getCjHp());
                BigDecimal jlHp = caiwuPankui.getJlHp() == null ? new BigDecimal(0) : new BigDecimal(caiwuPankui.getJlHp());
                BigDecimal jsHp = caiwuPankui.getJsHp() == null ? new BigDecimal(0) : new BigDecimal(caiwuPankui.getJsHp());
                BigDecimal pbHp = caiwuPankui.getPbHp() == null ? new BigDecimal(0) : new BigDecimal(caiwuPankui.getPbHp());
                BigDecimal heji = cjHp.add(qjyHp).add(jlHp).add(jsHp).add(pbHp);

                if (heji.compareTo(new BigDecimal(0)) != 0) {
                    pankui.setHeji(String.valueOf(heji));
                }

            } else if (huopeiDto.getShopName() != null && huopeiDto.getShopName().equals("酱料盘亏")) {

                pankui.setJlPk(huopeiDto.getClassName());//酱料盘亏
                pankui.setJlMp(huopeiDto.getProName());//酱料免赔
                pankui.setJlSoup(huopeiDto.getUnit());//酱料加汤
                pankui.setJlHp(huopeiDto.getThNum());//酱料货赔
                huopeiDto.setJlHp(pankui.getJlHp());

                BigDecimal jlHp = pankui.getJlHp() == null ? new BigDecimal(0) : new BigDecimal(pankui.getJlHp());
                BigDecimal qjyHp = caiwuPankui.getQjyHp() == null ? new BigDecimal(0) : new BigDecimal(caiwuPankui.getQjyHp());
                BigDecimal cjHp = caiwuPankui.getCjHp() == null ? new BigDecimal(0) : new BigDecimal(caiwuPankui.getCjHp());
                BigDecimal jsHp = caiwuPankui.getJsHp() == null ? new BigDecimal(0) : new BigDecimal(caiwuPankui.getJsHp());
                BigDecimal pbHp = caiwuPankui.getPbHp() == null ? new BigDecimal(0) : new BigDecimal(caiwuPankui.getPbHp());
                BigDecimal heji = cjHp.add(qjyHp).add(jlHp).add(jsHp).add(pbHp);

                if (heji.compareTo(new BigDecimal(0)) != 0) {
                    pankui.setHeji(String.valueOf(heji));
                }

            } else if (huopeiDto.getShopName() != null && huopeiDto.getShopName().equals("酒水盘亏")) {

                pankui.setJsPk(huopeiDto.getClassName());//酒水盘亏
                pankui.setJsMp(huopeiDto.getProName());//酒水免赔
                pankui.setJsSoup(huopeiDto.getUnit());//酒水加汤
                pankui.setJsHp(huopeiDto.getThNum());//酒水货赔
                huopeiDto.setJsHp(pankui.getJsHp());

                BigDecimal jsHp = pankui.getJsHp() == null ? new BigDecimal(0) : new BigDecimal(pankui.getJsHp());
                BigDecimal jlHp = caiwuPankui.getJlHp() == null ? new BigDecimal(0) : new BigDecimal(caiwuPankui.getJlHp());
                BigDecimal qjyHp = caiwuPankui.getQjyHp() == null ? new BigDecimal(0) : new BigDecimal(caiwuPankui.getQjyHp());
                BigDecimal cjHp = caiwuPankui.getCjHp() == null ? new BigDecimal(0) : new BigDecimal(caiwuPankui.getCjHp());
                BigDecimal pbHp = caiwuPankui.getPbHp() == null ? new BigDecimal(0) : new BigDecimal(caiwuPankui.getPbHp());
                BigDecimal heji = cjHp.add(qjyHp).add(jlHp).add(jsHp).add(pbHp);

                if (heji.compareTo(new BigDecimal(0)) != 0) {
                    pankui.setHeji(String.valueOf(heji));
                }

            } else if (huopeiDto.getShopName() != null && huopeiDto.getShopName().equals("平板电脑应有库存")) {
                pankui.setPbKc(huopeiDto.getClassName());//平板库存
                pankui.setPbPd(huopeiDto.getProName());//平板盘点
                pankui.setPbHp(huopeiDto.getThNum());//平板货赔
                huopeiDto.setPbHp(pankui.getPbHp());

                BigDecimal pbHp = pankui.getPbHp() == null ? new BigDecimal(0) : new BigDecimal(pankui.getPbHp());
                BigDecimal jsHp = caiwuPankui.getJsHp() == null ? new BigDecimal(0) : new BigDecimal(caiwuPankui.getJsHp());
                BigDecimal jlHp = caiwuPankui.getJlHp() == null ? new BigDecimal(0) : new BigDecimal(caiwuPankui.getJlHp());
                BigDecimal qjyHp = caiwuPankui.getQjyHp() == null ? new BigDecimal(0) : new BigDecimal(caiwuPankui.getQjyHp());
                BigDecimal cjHp = caiwuPankui.getCjHp() == null ? new BigDecimal(0) : new BigDecimal(caiwuPankui.getCjHp());
                BigDecimal heji = cjHp.add(qjyHp).add(jlHp).add(jsHp).add(pbHp);

                if (heji.compareTo(new BigDecimal(0)) != 0) {
                    pankui.setHeji(String.valueOf(heji));
                }

            }

            pankui.setShopCode(huopeiDto.getShopCode());//门店编号
            pankui.setBeginTime(huopeiDto.getBeginTime());

            pankuiMapper.update(pankui);
            i = 3;

//            if (i != 0){
//                //推送店长
//                String now = DateUtil.getNow();//当前时间
//                //查询店名
//                String dm = huopei.getShopName();
//                //备注
//                String note = huopei.getNote();
//
//                String data = dm + "财务已提交货赔单";
//                JSONObject tempObj = weChatSendTempMsgService.setTempParam(dm, note, "货赔管理", "货赔管理", now, data);
//
//                //店长openID
//                String dz = huopeiMapper.selectDz(huopei.getShopCode());
//                if (ToolUtil.isEmpty(dz)) {
//                    //事务回滚
//                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//                    logger.error("未找到店长微信openid,{}", BusExceptionEnum.NO_WX_ROLE);
////                    throw new BusException(BusExceptionEnum.NO_WX_ROLE);
//                    return ResponseData.error("推送失败，请联系店长绑定微信！");
//                }
//                String[] openids = {dz};
//                //推送消息
//                weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, tempObj);
//                logger.info("=======已推送店长消息======");
//            }
        }
        return ResponseData.success();
    }


//    @Override
//    public LayuiPageInfo list(List dm, Date beginTime, Date endTime) {
//        Page pageContext = getPageContext();
//        IPage page = huopeiMapper.list(pageContext, dm, beginTime, endTime);
//        return LayuiPageFactory.createPageInfo(page);
//    }

    @Override
    public LayuiPageInfo list(List dm, String timeLimit) {
        Page pageContext = getPageContext();
        IPage page = huopeiMapper.list(pageContext, dm, timeLimit);
        return LayuiPageFactory.createPageInfo(page);
    }

    @Override
    public List dzList(String name) {
        return huopeiMapper.dzList(name);
    }

    @Override
    public List listDz(String name) {
        return huopeiMapper.listDz(name);
    }

    @Override
    public List kjList(String name) {
        return huopeiMapper.kjList(name);
    }



    @Override
    public List dmList(String name) {
        return huopeiMapper.dmList(name);
    }

    /**
     * 审核
     *
     * @param huopei
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int audit(Huopei huopei) {

        //修改状态,所有修改操作数据库新增条数必须都大于0才会提交事务
        StringBuilder result = new StringBuilder();
        // 数据库修改条数
        int count = 0;

        //当前登陆者角色
        List<String> roleNames = LoginContextHolder.getContext().getUser().getRoleNames();

        String now = DateUtil.getNow();//当前时间
        //查询店名
        String dm = huopei.getShopName();

        //会计审核通过
//        if (roleNames.contains("会计") && huopei.getStatus() == 3){
        if (roleNames.contains("会计") && huopei.getStatus() == 1) {
            huopei.setStatus(3);//会计审核通过
            count = huopeiMapper.update(huopei);
            result.append(count > 0 ? 1 : 0);

            if (count > 0) {

                //备注
                String note = huopei.getNote();

                String data = dm + "财务已审核完成货赔";
                JSONObject tempObj = weChatSendTempMsgService.setTempParam(dm, note, "货赔管理", "货赔管理", now, data);

                //通知店长和人事
                //店长openID
                String dz = huopeiMapper.selectDz(huopei.getShopCode());

                //人事openID
                Long deptId = 1268783244079915009L;
                //查询人事openID
                List<String> list = userMapper.listOpenids(deptId);
                if (ToolUtil.isEmpty(list)) {
                    //事务回滚
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    logger.error("未找到人事微信openid,{}", BusExceptionEnum.NO_WX_ROLE);
//                    throw new BusException(BusExceptionEnum.NO_WX_ROLE);
                    return 1;
                }
                if (ToolUtil.isEmpty(dz)){
                    //事务回滚
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    logger.error("未找到店长微信openid,{}", BusExceptionEnum.NO_WX_ROLE);
//                    throw new BusException(BusExceptionEnum.NO_WX_ROLE);
                    return 2;
                }

                list.add(dz);
                String[] openids = list.toArray(new String[list.size()]);
                //推送消息
                weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, tempObj);
                logger.info("=======已推送人事和店长消息======");
                return 0;

            } else {
                throw new BusException(BusExceptionEnum.Err_UPDATE_STATUS);
            }

            //店长审核通过
//        }else if(roleNames.contains("店长报销单管理") && huopei.getStatus() == 2){
        } else if (roleNames.contains("店长报销单管理") && huopei.getStatus() == 1) {
            huopei.setStatus(2);//店长审核通过
            count = huopeiMapper.update(huopei);
            result.append(count > 0 ? 1 : 0);

            if (count > 0) {

                //备注
                String note = huopei.getNote();

                String data = dm + "店长已审核完成货赔";
                JSONObject tempObj = weChatSendTempMsgService.setTempParam(dm, note, "货赔管理", "货赔管理", now, data);

                //通知会计
                List<String> cw = huopeiMapper.selectCw(huopei.getCreateUser());

                if (ToolUtil.isEmpty(cw)) {
                    //事务回滚
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    logger.error("未找到财务微信openid,{}", BusExceptionEnum.NO_WX_ROLE);
//                    throw new BusException(BusExceptionEnum.NO_WX_ROLE);
                    return 3;
                }
                String[] openids = cw.toArray(new String[cw.size()]);
                //推送消息
                weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, tempObj);
                logger.info("=======已推送会计消息======");
                return 0;

            } else {
                throw new BusException(BusExceptionEnum.Err_UPDATE_STATUS);
            }
        }

        if (result.indexOf("0") >= 0) {
            //事务回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return 1;
        } else {
            return 0;
        }

//        return 0;
       // return ResponseData.success();
    }

    /**
     * 会计通知店长提交完成
     *
     * @param huopei
     */
    @Override
    @Transactional
    public int remind(Huopei huopei) {

        huopei.setStatus(7);//推送店长
        int n = huopeiMapper.update(huopei);
        if (n > 0){
            //推送店长
            String now = DateUtil.getNow();//当前时间
            //查询店名
//        String dm = huopei.getShopName();
            String dm = huopeiMapper.selectDm(huopei.getShopCode());
            //备注
            String note = huopei.getNote();

            String data = dm + "财务已提交货赔单";
            JSONObject tempObj = weChatSendTempMsgService.setTempParam(dm, note, "货赔管理", "货赔管理", now, data);

            //店长openID
            String dz = huopeiMapper.selectDz(huopei.getShopCode());
            if (ToolUtil.isEmpty(dz)) {
                //事务回滚
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                logger.error("未找到店长微信openid,{}", BusExceptionEnum.NO_WX_ROLE);
//                    throw new BusException(BusExceptionEnum.NO_WX_ROLE);
//            return ResponseData.error("推送失败，请联系店长绑定微信！");
                return 0;
            }
            String[] openids = {dz};
            //推送消息
            weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, tempObj);
            logger.info("=======已推送店长消息======");
//        return ResponseData.success();
        }

        return 1;
    }
}
